package api

import (
	"github.com/Shopify/sarama"
	"github.com/kataras/iris/v12"
	"github.com/shopspring/decimal"
	"ir/core/db"
	"ir/models/structs"
	"ir/models/tables"
	"ir/services"
	"ir/utils"
	"ir/utils/response"
	"log"
	"time"
)

func HandleOrder(ctx iris.Context) {
	var goodsOrder structs.GoodsOrder
	err := ctx.ReadJSON(&goodsOrder)
	resp := response.New(ctx)
	if err != nil {
		log.Println(err.Error())
		resp.SetMessage("参数解析失败").Set("err", err.Error()).Error()
		return
	}
	iSide := goodsOrder.Side
	var order structs.Order
	if iSide == 1 || iSide == 2 {
		now := time.Now().UnixNano()
		ip := utils.GetIp(ctx.Request())
		orderBook := tables.OrderBook{
			Sn:      goodsOrder.OrderSn,
			UserId:  goodsOrder.AccountId,
			Price:   goodsOrder.Price,
			Amount:  goodsOrder.Amount,
			Total:   goodsOrder.Amount,
			Symbol:  goodsOrder.Symbol,
			Side:    iSide,
			Created: now,
			Ip:      ip,
		}

		// 订单入库
		order, err = services.PickTradeOrderData(orderBook)
		if err != nil {
			log.Println("add order err", err)
			resp.SetMessage("订单入库失败").Error()
			return
		}
	} else if iSide == 3 {
		dbOrderBook := new(tables.OrderBook)
		var has bool
		conn := db.Conn()
		has, err = conn.Where("sn=? and user_id=?", goodsOrder.OrderSn, goodsOrder.AccountId).Get(dbOrderBook)
		if !has {
			resp.SetMessage("订单不存在").Error()
			return
		}
		if dbOrderBook.Status != 100 && dbOrderBook.Locked == 0 {
			affected, _ := conn.Cols("locked").Where("id=? and ver=?", dbOrderBook.Id, dbOrderBook.Ver).Update(tables.OrderBook{
				Locked: 1,
				Ver:    dbOrderBook.Ver + 1,
			})
			if affected > 0 {
				dAmount, _ := decimal.NewFromString(dbOrderBook.Amount)
				dPrice, _ := decimal.NewFromString(dbOrderBook.Price)
				fAmount, _ := dAmount.Float64()
				fPrice, _ := dPrice.Float64()
				order.SymbolOrder = structs.SymbolOrder{
					ID:      goodsOrder.OrderSn,
					UserId:  goodsOrder.AccountId,
					Amount:  fAmount,
					Price:   fPrice,
					Side:    dbOrderBook.Side,
					Created: dbOrderBook.Created,
				}
				order.Type = "cancel"
				order.Symbol = dbOrderBook.Symbol
			}
		} else {
			resp.SetMessage("订单已撮合或锁定").Error()
		}
	} else {
		resp.SetMessage("参数错误").Error()
		return
	}

	producer := services.CreateProducer()
	producer.Input() <- &sarama.ProducerMessage{
		Topic: "orders",
		Value: sarama.StringEncoder(order.ToJSON()),
	}
	resp.Success()
	return
}
